namespace CRM_Perf_BenchMark
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    using System.Net;
    using System.Text;
    using System.Xml;
    
    /// <summary>
    /// Start at Settings
    /// 1. Select Business Management
    /// 2. Select Relationship Roles
    /// 3. Click New
    /// 4. Enter Name data
    /// 5. Save and Close
    /// </summary>

    public class CreateRelationship : CrmWebTest
    {
        public void CreateRelationship_PreWebTest(object sender, PreWebTestEventArgs e)
        {
            EntityRequest er = new EntityRequest();
            er.Type = EntityNames.Users;
            er.ReturnAs = EntityNames.Users;
            er.ParentID = EntityManager.Instance.OrgId;

            System.Collections.Hashtable userProps = new System.Collections.Hashtable();
            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                userProps.Add("role", e.WebTest.Context["UserRole"]);
                er.Props = userProps;
            }
            
            System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

            user = (CRMEntity)Entities[EntityNames.Users];

            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);

            orgId = new Guid(user["organizationid"]);

            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];            
        }
        
        public void CreateRelationship_PostWebTest(object sender, PostWebTestEventArgs e)
        {
            EntityManager.Instance.FreeEntity(user);
        }

        public CreateRelationship()
        {
            WebRequest.RegisterPrefix("crm", new crmRequestFactory());
            gridXml = GridXmlHelper.RelationshipPageView(-1, relationshipView, null);

            this.Proxy = null;           
            PreWebTest += new EventHandler<PreWebTestEventArgs>(CreateRelationship_PreWebTest);
            PostWebTest += new EventHandler<PostWebTestEventArgs>(CreateRelationship_PostWebTest);
        }

        public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        {
            this.BeginTransaction("CreateRelationship");

            tools_business_business_aspx businessHome = new tools_business_business_aspx(user);
            yield return (businessHome);

            businessHome = new tools_business_business_aspx(user);
            businessHome.pid = 12;
            yield return (businessHome);

            tools_relationshiprolemanager_home_aspx rrm = new tools_relationshiprolemanager_home_aspx(user);
            yield return (rrm);

            tools_relationshiproleeditor_edit_aspx rre = new tools_relationshiproleeditor_edit_aspx(user);
            yield return (rre);

            rre = new tools_relationshiproleeditor_edit_aspx(user);
            string name = Utils.GetRandomString(5,10);
            rre.crmFormSubmitXml = EntityXmlHelper.GetCreateRelationshipRoleXml(name); //relRole.Serialize();
            WRPCInfo rpcInfo = Utils.GenerateWRPCToken(tools_relationshiproleeditor_edit_aspx.url, user, tokenKey);
            rre.CRMWRPCToken = rpcInfo.token;
            rre.CRMWRPCTokenTimeStamp = rpcInfo.timeStamp;
            rre.crmFormSubmitMode = 1;
            rre.crmFormUserModified = true;
            rre.crmFormSubmitOnline = 1;
            rre.crmFormSubmitObjectType = 4500;
            rre.crmFormSubmitSecurity = 65591;
            yield return (rre);

            AppGridWebService.AppGridWebService agws = new AppGridWebService.AppGridWebService();
            CrmRequest wtrRefresh = null;
            try { agws.Refresh(gridXml); }
            catch (crmException x)
            {
                wtrRefresh = (CrmRequest)x.wtr;
                wtrRefresh.Url = Utils.ReplaceServerName(wtrRefresh.Url, user);

                string urlPath = wtrRefresh.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                WebTestRequestHeader headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtrRefresh.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtrRefresh.Headers.Add(headerItem);
                wtrRefresh.Method = "Post";
            }
            yield return (wtrRefresh);

            this.EndTransaction("CreateRelationship");
        }
                
        private CRMEntity user;
        private string gridXml;
        private string crmServer;
        private string tokenKey;
        private static string relationshipView = "938894EC-71AA-4937-A56B-262957B44A02";

        private Guid orgId;
    }
}